<!-- copy orderitem中的addAmout by yf 9/1 -->
<template>
  <div>
    <div @click="clickHandler" class="clickBtn">
      <el-input v-model="formData[formKey].text" readonly>
        <template slot="append">
          <a href="javascript:;" style="font-size: 20px">
            <i class="el-icon-more"></i>
          </a>
        </template>
      </el-input>
    </div>
    <el-dialog
      width="80%"
      title="省付费账户"
      :visible.sync="show"
      class="m-dialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form label-width="80px">
        <el-row :gutter="3" class="m-contain">
          <el-col :span="5">
            <el-form-item label="省份:" class="u-ipt" required>
              <el-select
                @change="proSelectChange"
                :disabled="proDisabled"
                v-model="queryData.proSelect"
                placeholder="请选择"
                class="m-select"
              >
                <el-option
                  v-for="item in proList"
                  :key="item.commonRegionId"
                  :label="item.regionName"
                  :value="item.commonRegionId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="地市:" class="u-ipt">
              <el-select
                v-model="queryData.citySelect"
                placeholder="请选择"
                class="m-select"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.commonRegionId"
                  :label="item.regionName"
                  :value="item.commonRegionId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="3">
          <el-col :span="5">
            <el-form-item label="客户名称:" class="u-ipt" required>
              <el-input
                placeholder="请输入内容"
                v-model="getProData.custName"
                class="input-with-select"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="省客户编码:" class="u-ipt">
              <el-input
                placeholder="请输入内容"
                v-model="getProData.custCode"
                class="input-with-select"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="省账户ID:" class="u-ipt">
              <el-input
                placeholder="请输入内容"
                v-model="getProData.proAId"
                class="input-with-select"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="省客户ID:" class="u-ipt">
              <el-input
                placeholder="请输入内容"
                v-model="getProData.proId"
                class="input-with-select"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" class="btnClass">
            <el-button class="checkBtn" type="primary" @click="addAcc">
              新建省账户
            </el-button>
          </el-col>
          <el-col :span="5">
            <el-form-item label="省账户编码:" class="u-ipt">
              <el-input
                placeholder="请输入内容"
                v-model="getProData.proAccCode"
                class="input-with-select"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="证件类型:" class="u-ipt">
              <el-select
                v-model="getProData.idType"
                placeholder="请选择"
                class="m-select"
              >
                <el-option
                  v-for="item in selectInfo[1].val"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="证件号码:" class="u-ipt">
              <el-input
                placeholder="请输入内容"
                v-model="getProData.idNum"
                class="input-with-select"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="省接入号码:" class="u-ipt">
              <el-input
                placeholder="请输入内容"
                v-model="getProData.proInNum"
                class="input-with-select"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" class="btnClass">
            <el-button class="checkBtn" type="primary" @click="checkProAcc">
              查询
            </el-button>
            <el-button class="checkBtn" type="primary" @click="resetForm">
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        v-loading="loading"
        ref="proAccList"
        :data="
          proAccList.slice(
            (proTablePage.pageIndex - 1) * proTablePage.pageSize,
            proTablePage.pageIndex * proTablePage.pageSize
          )
        "
        border
        stripe
        max-height="300"
        :header-cell-style="{
          background: '#F2F2F2',
          color: '#333',
        }"
        tooltip-effect="dark"
        style="width: 100%"
        @row-click="dbCellHandler"
      >
        <el-table-column
          prop="REGION_NAME"
          label="地市"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="PROVINCE_ACCOUNT_NANE"
          label="账户名称"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="PROVINCE_ACCOUNT_NUMBER"
          label="省账户编码"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="PROVINCE_ACCOUNT_ID"
          label="省账户ID"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="PROVINCE_CUST_ID"
          label="省客户ID"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="STATUS_DATE"
          label="创建时间"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @current-change="proPageChange"
        :current-page="parseInt(proTablePage.pageIndex)"
        :page-size="parseInt(proTablePage.pageSize)"
        layout="total, prev, pager, next, jumper"
        :total="parseInt(proTablePage.rowCount)"
        class="m-pagination"
      >
      </el-pagination>
      <div style="height: 20px"></div>
    </el-dialog>
    <el-dialog
      width="80%"
      title="新建省账户"
      :visible.sync="innerShow"
      class="m-dialog"
      :close-on-click-modal="false"
      @close="close"
      append-to-body
    >
      <el-form
        style="margin-top: 10px"
        ref="createNewAccountManagerRef"
        :rules="createNewAccountManagerRules"
        :model="createNewAccountManagerForm"
        label-width="100px"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="省客户ID:" prop="custId" class="proCust">
              <div style="position: relative">
                <el-input
                  @click.native="drawerShow"
                  v-model="createNewAccountManagerForm.custId"
                  readonly
                >
                  <template slot="append"
                    ><i class="el-icon-more"></i
                  ></template>
                </el-input>
              </div>
              <province-custpicker
                ref="provinceCust"
                @updateshow="custPickerShowHandler"
                @pickerEnd="pickerEnd"
                @prohsChange="prohsChange"
                :show="orderPreTaskVisible"
                :Data="provData"
                :tableLoading="true"
              >
              </province-custpicker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账户名称:" prop="acctName" class="u-ipt">
              <el-input
                v-model="createNewAccountManagerForm.acctName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮政编码:" class="u-ipt" prop="postCode">
              <el-input
                v-model="createNewAccountManagerForm.postCode"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账单投递方式:" class="u-ipt">
              <el-select
                v-model="createNewAccountManagerForm.billPostType"
                class="m-select"
              >
                <el-option
                  v-for="item in selectInfo[0].val"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="账单邮递地址:"
              class="u-ipt"
              required
              prop="postAddress"
            >
              <el-input
                v-model="createNewAccountManagerForm.postAddress"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行名称:" class="u-ipt" prop="bankName">
              <el-input
                v-model="createNewAccountManagerForm.bankName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="银行帐号:" class="u-ipt" prop="paymentAccount">
              <el-input
                v-model="createNewAccountManagerForm.paymentAccount"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户描述:" class="u-ipt" prop="accountDesc">
              <el-input
                type="textarea"
                v-model="createNewAccountManagerForm.accountDesc"
                :autosize="{ minRows: 2, maxRows: 4 }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注:" class="u-ipt" prop="remark">
              <el-input
                type="textarea"
                v-model="createNewAccountManagerForm.remark"
                :autosize="{ minRows: 2, maxRows: 4 }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="text-c m-btn-box">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="saveAdddCustAccountHandel"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CreateNewAccountManager from "@/api/customer/CreateNewAccountManager";
import ProvinceCustpicker from "@/components/order/ProvinceCustpicker";
import CustRelationManage from "@/api/customer/CustRelationManage";
import OrderService from "@/api/order/OrderService.js";
import { mapState } from "vuex";
import { Loading } from "element-ui";
export default {
  name: "AddAmount",
  components: {
    ProvinceCustpicker,
  },
  props: {
    infors: {
      type: Object,
      default: {},
    },
    formData: {
      type: Object,
    },
    formKey: {
      type: String,
    },
  },
  data() {
    return {
      show: false,
      innerShow: false,
      loading: false,
      proAccList: [], //省账户列表
      proDisabled: false, //省是否可选择
      createNewAccountManagerForm: {
        //   账户名称
        acctName: "",
        //   客户名称-保存的时候不需要传递
        custName: "",
        // 客户主键-当选择客户的时候用来存放选择客户的custId
        custId: "",
        // 账户名称
        acctName: "",
        // 账户类型
        acctBillingType: "10260001",
        // 邮政编码
        postCode: "",
        // 账单投递方式
        billPostType: "11",
        // 银行名称
        bankName: "",
        // 银行账号
        paymentAccount: "",
        // 账单邮递地址
        postAddress: "",
        //账户描述
        accountDesc: "",
        // 备注
        remark: "",
        commonregionId: "",
      },
      // 校验规则
      createNewAccountManagerRules: {
        custId: [
          { required: true, message: "请选择省客户", trigger: "change" },
        ],
        acctName: [
          {
            required: true,
            message: "请输入账户名称",
            trigger: ["blur", "change"],
          },
        ],
        postAddress: [
          {
            required: true,
            message: "请输入账单邮递地址",
            trigger: ["blur", "change"],
          },
        ],
      },
      // 下拉框的取值
      selectInfo: [
        {
          flag: "bill_post_type",
          val: [],
        },
        {
          flag: "cert_type",
          val: [],
        },
      ],
      getProData: {
        custName: "",
        custCode: "",
        proId: "",
        proAId: "",
        proAccCode: "",
        idType: "",
        idNum: "",
        proInNum: "",
      }, //查询省客户列表
      proTablePage: {
        pageIndex: 1, //当前页码
        pageSize: 5, //每页多少条
        rowCount: 0, //总条数
      }, //省客户查询列表
      queryData: {
        proSelect: "", //选择的省
        citySelect: "", //选择的城市
      }, //选择省市
      cityInfo: {},
      proList: [], //省列表
      cityList: [], //城市列表
      userInfo: {},
      modelVal: "",
      proCustId: "",
      orderPreTaskVisible: false,
      provData: {},
    };
  },
  mounted() {
    this.formData;
    this.userInfo = JSON.parse(sessionStorage.getItem("crm3-userinfo")) || {};
    this.initValueIdType(); //查询证件类型
    this.getRegionCodeList(); //查询省code
    this.getProData.custName = this.infors.custName;
    this.createNewAccountManagerForm.custId =
      this.respCustId != null && this.respCustId != "null"
        ? this.respCustId
        : "";
    sessionStorage.setItem("accVal", 0);
  },
  computed: {
    ...mapState("orders", ["respCustId"]),
  },
  watch: {
    show(val) {
      if (val) {
        Object.keys(this.formData).forEach((key) => {
          //客户名称
          if (this.formData[key].fieldId === "CUST_NAME") {
            this.getProData.custName = this.formData[key].value;
          }
          //客户编码
          if (this.formData[key].fieldId === "CUST_NUMBER") {
            this.getProData.custCode = this.formData[key].value;
          }
          //省客户id RESP_CUST_ID
          if (this.formData[key].fieldId === "RESP_CUST_ID") {
            this.getProData.proId = this.formData[key].value;
          }
        });
        //新建账户的客户id
        this.createNewAccountManagerForm.custId = this.getProData.proId;
      }
    },
  },
  methods: {
    async initValueIdType() {
      let response = "";
      this.selectInfo.forEach(async (item, index) => {
        response = await CreateNewAccountManager.initValue({ flag: item.flag });
        if (response.code == 200) {
          this.selectInfo[index].val = response.meta.customers;
        }
      });
    },
    //查询省code
    async getRegionCodeList() {
      let reault = await OrderService.getRegionCodeList({
        regionId: this.userInfo.regionId,
        regionType: this.userInfo.regionType,
      });
      if (reault.code == 200) {
        this.cityInfo = reault.meta;
        this.getProvinceList();
      } else {
        this.getProvinceList();
      }
    },
    //查询省账户列表
    async getProAcc() {
      let parmas = {
        custName: this.getProData.custName,
        provinceCustNumber: this.getProData.custCode,
        provinceId: this.queryData.proSelect,
        lanId: this.queryData.citySelect,
        provinceAccountId: this.getProData.proAId,
        provinceAccountNumber: this.getProData.proAccCode,
        provinceCustId: this.getProData.proId,
        certType: this.getProData.idType,
        certNum: this.getProData.idNum,
        accNum: this.getProData.proInNum,
      };
      this.loading = true;
      const response = await CreateNewAccountManager.getAccProList(parmas);
      this.loading = false;
      if (response.code == 200) {
        this.proAccList = response.meta.customers;
        if (this.proAccList.length > 0) {
          this.proAccList.forEach((item) => {
            item.STATUS_DATE = item.STATUS_DATE
              ? this.changeDate(item.STATUS_DATE)
              : "";
          });
        }
        this.proTablePage.rowCount = response.meta.rowCount;
      }
    },
    //时间转换
    changeDate(val) {
      var time = new Date(val.split("Z")[0]);
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      return (
        y +
        "-" +
        this.add0(m) +
        "-" +
        this.add0(d) +
        " " +
        this.add0(h) +
        ":" +
        this.add0(mm) +
        ":" +
        this.add0(s)
      );
    },
    add0(m) {
      return m < 10 ? "0" + m : m;
    },
    //查询省账户事件
    checkProAcc() {
      if (this.queryData.proSelect == "") {
        this.$alert("省份不能为空", "警告", {
          type: "warning",
          confirmButtonText: "关闭",
        });
        return;
      }
      this.proTablePage.pageIndex = 1;
      this.getProAcc();
    },
    //重置按钮
    resetForm() {
      this.getProData = {
        custName: this.getProData.custName,
        custCode: "",
        proId: "",
        proAId: "",
        proAccCode: "",
        idType: "",
        idNum: "",
        proInNum: "",
      };
      this.queryData.citySelect = "";
      if (!this.proDisabled) return (this.queryData.proSelect = "");
    },
    custNamehandel() {},
    //省列表改变当前页触发事件
    proPageChange(val) {
      this.proTablePage.pageIndex = val;
    },
    //获取省
    async getProvinceList() {
      const response = await CustRelationManage.getProvinceList();
      if (response.code == 200) {
        this.proList = response.meta;
        if (this.userInfo.orgId != 1944640) {
          this.queryData.proSelect = this.cityInfo.proArr[0].regionId;
          this.getLanList(this.queryData.proSelect);
          this.proDisabled = true;
        }
        if (
          this.userInfo.regionType == 1300 ||
          this.userInfo.regionType == 1400
        ) {
          this.queryData.citySelect = this.cityInfo.lenArr[0].regionId;
        }
      }
    },
    //城市列表
    async getLanList(val) {
      const response = await CustRelationManage.getLanList({
        parRegionId: val,
      });
      if (response.code == 200) {
        this.cityList = response.meta;
      }
    },
    //改变省列表
    proSelectChange(val) {
      this.queryData.citySelect = "";
      this.getLanList(val);
    },
    clickHandler() {
      this.show = true;
      this.getProData = {
        custName: this.getProData.custName,
        custCode: "",
        proId: "",
        proAId: "",
        proAccCode: "",
        idType: "",
        idNum: "",
        proInNum: "",
      };
      this.getProAcc(); //查询省客户列表
    },
    //新建账户
    addAcc() {
      if (this.queryData.proSelect == "") {
        this.$alert("省份不能为空", "警告", {
          type: "warning",
          confirmButtonText: "关闭",
        });
        return;
      }
      if (
        this.queryData.citySelect == "" &&
        this.queryData.proSelect != "500182716" &&
        this.queryData.proSelect != "500182954" &&
        this.queryData.proSelect != "500182957" &&
        this.queryData.proSelect != "500181505"
      ) {
        this.$alert("地市不能为空", "警告", {
          type: "warning",
          confirmButtonText: "关闭",
        });
        return;
      }
      this.innerShow = true;
    },
    custNameCurrentChangeEvent() {},
    //新建账户-保存-点击事件
    saveAdddCustAccountHandel() {
      this.$refs.createNewAccountManagerRef.validate((valid) => {
        if (valid) {
          this.saveAdddCustAccount();
        } else {
          return false;
        }
      });
    },
    //新建账户-保存
    async saveAdddCustAccount() {
      let params = {
        acctName: this.createNewAccountManagerForm.acctName,
        provinceCustId: this.createNewAccountManagerForm.custId,
        custId: this.infors.custId,
        accountDesc: this.createNewAccountManagerForm.accountDesc,
        staffId: this.userInfo.staffId,
        remark: this.createNewAccountManagerForm.remark,
        acctBillingType: this.createNewAccountManagerForm.acctBillingType,
        billPostType: this.createNewAccountManagerForm.billPostType,
        postAddress: this.createNewAccountManagerForm.postAddress,
        postCode: this.createNewAccountManagerForm.postCode,
        bankName: this.createNewAccountManagerForm.bankName,
        paymentAccount: this.createNewAccountManagerForm.paymentAccount,
        commonRegionId: this.queryData.citySelect
          ? this.queryData.citySelect
          : this.queryData.proSelect,
      };
      let loadingInstance = Loading.service({ fullscreen: true });
      let result = await CreateNewAccountManager.createAccount(params);
      loadingInstance.close();
      if (result.code == 200) {
        if (result.meta.resultCode == 0) {
          if (result.meta.provResultCode == "0000") {
            this.$confirm("新建账户成功", "提示", {
              confirmButtonText: "确定",
              type: "success",
              center: true,
              showCancelButton: false,
            })
              .then(() => {
                this.innerShow = false;
                this.show = false;
                sessionStorage.setItem("accVal", 1);
                this.modelVal = result.meta.province_account_number
                  ? result.meta.province_account_number
                  : result.meta.province_account_id;
                this.formData[this.formKey].value = this.modelVal;
                this.formData[this.formKey].text = this.modelVal;
                this.$emit("getAccData", result.meta);
              })
              .catch(() => {});
          } else {
            this.$message({
              showClose: true,
              message: "新建集团账户成功，同步省账户失败！",
              type: "error",
            });
          }
        } else {
          this.$message({
            showClose: true,
            message: result.meta.resultMsg,
            type: "error",
          });
        }
      }
    },
    //父级更改控制dialog的显示隐藏
    custPickerShowHandler(val) {
      this.orderPreTaskVisible = val;
    },
    //省客户弹窗显隐
    drawerShow() {
      if (this.respCustId != null && this.respCustId != "null") return;
      this.provinceCustList();
      this.orderPreTaskVisible = true;
    },
    async provinceCustList() {
      //加载省客户关系
      let pageInfo = {
        pageIndex: 1,
        pageSize: 10,
      };
      let parmas = {
        qryType: "INTERFACE",
        PageFlag: "1", //固定
        custName: this.getProData.custName, //客户名称
        provRegionCode: this.userInfo.regionCode,
        commonRegionId: this.userInfo.regionId,
        listShowFlag: "orderShow", //固定
        ...pageInfo,
      };
      this.$refs.provinceCust.tableLoading = true;
      let result = await OrderService.provinceCustList(parmas);
      this.$refs.provinceCust.tableLoading = false;
      if (result.code == 200) {
        if (result.meta.customer && result.meta.customer.length > 0) {
          this.provData = result.meta;
        }
      }
    },
    pickerEnd(val) {
      this.createNewAccountManagerForm.custName = val.custName;
      this.createNewAccountManagerForm.custId = val.custId;
      this.$store.commit("orders/SET_RESP_CUSTID", val.custId);
    },
    async prohsChange(pageInfo) {
      let parmas = {
        qryType: "INTERFACE",
        PageFlag: "1", //固定
        custName: this.getProData.custName, //客户名称
        provRegionCode: this.userInfo.regionCode,
        commonRegionId: this.userInfo.regionId,
        listShowFlag: "orderShow", //固定
        ...pageInfo,
      };
      this.$refs.provinceCust.tableLoading = true;
      let result = await OrderService.provinceCustList(parmas);
      this.$refs.provinceCust.tableLoading = false;
      if (result.code == 200) {
        if (result.meta.customer.length > 0) {
          this.provData = result.meta;
        }
      }
    },
    // 取消
    close() {
      this.innerShow = false;
      this.$refs.createNewAccountManagerRef.resetFields();
      this.createNewAccountManagerForm.custId =
        this.respCustId != null && this.respCustId != "null"
          ? this.respCustId
          : "";
    },
    dbCellHandler(row) {
      this.show = false;
      sessionStorage.setItem("accVal", 1);
      this.modelVal = row.PROVINCE_ACCOUNT_NUMBER
        ? row.PROVINCE_ACCOUNT_NUMBER
        : row.PROVINCE_ACCOUNT_ID;
      this.formData[this.formKey].value = this.modelVal;
      this.formData[this.formKey].text = this.modelVal;
      this.$emit("getrow", row);
    },
  },
};
</script>

<style lang="scss" scoped>
.clickBtn {
  ::v-deep .el-input-group--append .el-input__inner,
  .el-input-group__prepend {
    cursor: pointer;
  }
}
.m-pagination {
  margin-top: 20px;
  text-align: center;
}
.m-contain {
  margin-top: 20px;
}
.u-ipt ::v-deep .el-form-item__label {
  position: relative;
  top: 5px;
}
.btnClass {
  position: relative;
  top: 5px;
}
.m-btn-box {
  padding: 0.2rem;
  text-align: center;
}
.proCust {
  position: relative;
  top: 7px;
}
</style>
